package com.zhiwei.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhiwei.mapper.UserMapper;
import com.zhiwei.pojo.User;
import com.zhiwei.vo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> getlist() {
        return userMapper.selectList(new QueryWrapper<User>().eq("isystem", 0));
    }

    @Override
    public UserInfo login(User user) {
        String pwd = user.getPassword()+"智为";
        pwd = DigestUtils.md5DigestAsHex(pwd.getBytes());
        user.setPassword(pwd);
        QueryWrapper<User> wrapper = new QueryWrapper<>(user);
        User userDB = userMapper.selectOne(wrapper);
        if (userDB == null){
            return null;
        }
        UserInfo userInfo = new UserInfo();
        String token = UUID.randomUUID().toString().replace("-", "");
        return userInfo.setUser(userDB).setToken(token);
    }

    @Override
    public int addUser(User user) {
        String pwd = user.getPassword()+"智为";
        pwd = DigestUtils.md5DigestAsHex(pwd.getBytes());
        user.setPassword(pwd);
        return userMapper.insert(user);
    }

    @Override
    public User getUser(Integer userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public Integer findUser(String name) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("login_name", name);
        User user = userMapper.selectOne(wrapper);
        if (user != null){
            return 1;
        }
        return 0;
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public int getMsgNum(Integer userId) {
        User user = userMapper.selectById(userId);
        return user.getMsgNum();
    }
}
